package com.foryang.springcloud.config;

import com.foryang.springcloud.entity.SystemUser;
import com.foryang.springcloud.service.PermissionService;
import com.foryang.springcloud.service.UserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        SystemUser user = userService.getByUsername(name);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if(user != null){
            List<String> permissions = permissionService.getPermission(name);
            permissions.forEach(permission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission);
                grantedAuthorities.add(grantedAuthority);
            });
        }
        return new User(user.getUsername(), user.getPassword(),grantedAuthorities);
    }

}
